package com.heima.gateway.filter;

import com.heima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try {
//        1.将请求白名单放行
            String path = request.getURI().getPath();
            if (path.contains("/login")){
                return chain.filter(exchange);
            }
//        2.获取请求中的令牌
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isNotBlank(token)) {
    //        3.解析令牌
                Claims claims = AppJwtUtil.getClaimsBody(token);
                Object userId = claims.get("userId");
                Object userName = claims.get("userName");
    //        4.路由请求到目标微服务设置请求头：用户ID，用户名称
                request.mutate().header("userId",userId.toString());
                request.mutate().header("useName",userName.toString());
    //            放行
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            log.error("admin网关异常：{}",e);
            e.printStackTrace();
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
